﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using SmartMathLibrary.LinearEquationSolvers;

namespace SmartMathLibrary.NonlinearEquationSolvers
{
    /// <summary>
    /// This class provides the solving of a nonlinear system of equation by using the Broyden 
    /// method.
    /// </summary>
    [Serializable]
    public class BroydenNonLinearSystemSolver : AbstractRealNonLinearSystemSolver
    {
        /// <summary>
        /// Initializes a new instance of the <see cref="BroydenNonLinearSystemSolver"/> class.
        /// </summary>
        /// <param name="equationSystem">The nonlinear system of equation to solve.</param>
        public BroydenNonLinearSystemSolver(NonLinearEquationSystem equationSystem)
            : base(equationSystem)
        {
        }

        /// <summary>
        /// Initializes a new instance of the <see cref="BroydenNonLinearSystemSolver"/> class.
        /// </summary>
        /// <param name="equationSystemFunctions">The equation system functions.</param>
        public BroydenNonLinearSystemSolver(HardMultivariateRealFunction[] equationSystemFunctions)
            : base(equationSystemFunctions)
        {
        }

        /// <summary>
        /// Solves the nonlinear system of equation by using the Broyden method. The property 
        /// PrecisionError have to be checked after the calculation to be sure that the results 
        /// are correct.
        /// </summary>
        /// <param name="startValues">The start values for the calculation.</param>
        /// <param name="iterations">The maximum number of iterations.</param>
        /// <param name="precision">The precision of the result.</param>
        /// <returns>
        /// The approximated numeric results, which solves the nonlinear system of equation.
        /// </returns>
        public override GeneralVector SolveNonLinearSystem(GeneralVector startValues, int iterations, double precision)
        {
            if (startValues == (GeneralVector) null)
            {
                throw new ArgumentNullException("startValues");
            }

            if (startValues.Count != this.EquationSystem.EquationSystem.Length)
            {
                throw new ArgumentException(
                    "The number of components in the start vector has to be even with the number of equations.");
            }

            if (this.EquationSystem.EquationSystem.Length < 2)
            {
                throw new ArgumentException(
                    "The system of equation has to have to contain a minimum number of two equations.");
            }

            int iterationCount = 0;
            GeneralVector result = startValues.Copy();
            Matrix matrix = new IdentityMatrix(this.EquationSystem.EquationSystem.Length);
            GeneralVector parameterVector = new GeneralVector(this.EquationSystem.EquationSystem.Length);

            while (iterationCount < iterations)
            {
                double delta = 0.0;
                GeneralVector functionResults1 = this.EquationSystem.SolveAt(result);
                GaussLinearSystemSolver linearSystemSolver = new GaussLinearSystemSolver(matrix, functionResults1);
                GeneralVector s = linearSystemSolver.SolveLinearSystem();

                for (int i = 0; i < this.EquationSystem.EquationSystem.Length; i++)
                {
                    parameterVector[i] = result[i] - s[i];
                    delta += Math.Pow(s[i], 2);
                }

                if (delta <= Math.Abs(precision))
                {
                    break;
                }

                GeneralVector functionResults2 = this.EquationSystem.SolveAt(parameterVector);

                for (int i = 0; i < this.EquationSystem.EquationSystem.Length; i++)
                {
                    double tempuri = functionResults2[i] + functionResults1[i];

                    for (int j = 0; j < this.EquationSystem.EquationSystem.Length; j++)
                    {
                        tempuri -= matrix.GetValueAtPosition(i, j) * s[j];
                    }

                    for (int j = 0; j < this.EquationSystem.EquationSystem.Length; j++)
                    {
                        matrix.SetValueAtPosition(i, j, matrix.GetValueAtPosition(i, j) - tempuri
                                                                                          * s[j] / delta);
                    }
                }

                for (int i = 0; i < this.EquationSystem.EquationSystem.Length; i++)
                {
                    functionResults1[i] = functionResults2[i];
                    result[i] = parameterVector[i];
                }

                iterationCount++;
            }

            this.neededIterations = iterationCount;
            this.precisionError = (iterations == iterationCount);

            return result;
        }
    }
}